import { Controller, action } from "maishu-node-mvc";
import path = require("path");
import fs = require("fs");
import { settings } from "../settings";
import { errors } from "../errors";

export class ComponentController extends Controller {
    @action("/component/list")
    async componentList() {

        let files: { name: string, files: string[] }[] = []

        let componentsRoot = "components";

        let absolutePath = path.join(settings.staticRootDirectory, componentsRoot);
        if (!fs.existsSync(absolutePath))
            throw errors.pathNotExists(absolutePath)

        let componentDirs = fs.readdirSync(absolutePath);
        componentDirs.forEach(c => {

            let p = path.join(absolutePath, c);
            let stats = fs.lstatSync(p);
            if(stats.isDirectory()){
                let children = fs.readdirSync(p);
                files.push({ name: c, files: children })
            }
        })

        return files;
    }
}